package com.gupao.pattern.proxy.dynamicproxy.jdk.custom;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class GPClassLoader extends ClassLoader{

    private File classPathFile;

    public GPClassLoader(){
        String classPath=GPClassLoader.class.getResource("").getPath();
        classPathFile=new File(classPath);
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {

        FileInputStream in=null;
        ByteArrayOutputStream out=null;
        String className=GPClassLoader.class.getPackage().getName()+"."+name;
        try {
            if (classPathFile.exists()){
                File file = new File(classPathFile, name.replaceAll("\\.", "/") + ".class");

                in=new FileInputStream(file);
                out=new ByteArrayOutputStream();
                byte[] buff=new byte[1024];
                int len;
                while ((len=in.read(buff))!=-1){
                    out.write(buff,0,len);
                }
                return defineClass(className,out.toByteArray(),0,out.size());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (in!=null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (out!=null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


        return null;
    }
}
